/*************************************************
 File name : lcdinfo.c
 Create date : 2015-08-06 23:40
 Modified date : 2015-08-06 23:40
 Author : heqingde
 Email : hqd173@163.com
 
 ***********************************************/
#include "lcdinfo.h"
#include <linux/fb.h>


//初始化lcd
LcdDev *init_lcd(const char *dev)
{
	LcdDev *lcd = (LcdDev*)malloc(sizeof(LcdDev));
	if(lcd == NULL)
	{
		perror("init lcd fail");
		return NULL;
	}

	//打开lcd设备
	lcd->fd = open(dev, O_RDWR);
	if(lcd->fd < 0)
	{
		perror("open lcd fail");
		free(lcd);
		return NULL;
	}
	
	//取lcd信息
	int a;
	struct fb_var_screeninfo info;
	int ret = ioctl(lcd->fd, FBIOGET_VSCREENINFO, &info);
	if(ret < 0)
	{
		perror("get lcd info fail");
	}
	lcd->wscreen = info.xres;
	lcd->hscreen = info.yres;
	lcd->pixel = info.bits_per_pixel/8;

	//映射
	lcd->p = mmap(NULL,
		     lcd->wscreen*lcd->hscreen*lcd->pixel, 
		     PROT_READ|PROT_WRITE,
		     MAP_SHARED,
		     lcd->fd,
		     0);
	if(lcd->p == NULL)	
	{
		close(lcd->fd);
		free(lcd);
		perror("mmap fail");
		return NULL;
	}

	return lcd;
}

//释放lcd资源
bool destroy_lcd(LcdDev *lcd)
{
	if(lcd == NULL)
	{
		return false;
	}
	munmap(lcd->p, lcd->wscreen*lcd->hscreen*lcd->pixel);
	close(lcd->fd);
	free(lcd);
	return true;
}

//在lcd上绘制一个像素点
bool draw_pix(LcdDev *lcd, int x, int y, unsigned int color)
{
	if(lcd == NULL)
	{
		return false;
	}
	if(x > lcd->wscreen || y > lcd->hscreen)
	{
		return false;
	}

	*(lcd->p+y*lcd->wscreen+x) = color;
	return true;
}

//在lcd上绘制一行像素
bool draw_line_pix(LcdDev *lcd, int y,unsigned int *color, int length)
{
	if(lcd)
	{
		int len = lcd->wscreen<length?lcd->wscreen:length;
		unsigned int *p = lcd->p+y*lcd->wscreen;
		memcpy(p,color,len*lcd->pixel);
		return true;
	}else return false;
}

